'use server';
import { formatFindParams } from '@/pao/server/serverPrisma';
import { PrismaClient, Knowledge } from '@/data/prisma';

const prisma = new PrismaClient()

export async function query (filter: Record<string, any>
    , sorter: Record<string, any>
    , pageSize: number = 50
    , pageIndex: number = 1
    , columnFilterTypes: Record<string, string> = {}): Promise<{ rows: Knowledge[]; total: number; }>  {
    const subjects = await prisma.knowledge.findMany(formatFindParams(filter, sorter, pageSize, pageIndex, columnFilterTypes))
    return {rows:subjects as unknown as Knowledge[], total: subjects.length}
}

export async function deleteRow (row: Knowledge) {
    await prisma.knowledge.delete({ where: { id: row.id } })
}

export async function editRow (row: Knowledge) {
    await prisma.knowledge.update({  where: { id: row.id }, data: row })
}

export async function addRow(row: Knowledge) {
    await prisma.knowledge.create({ data: row })
}

export async function modifyRows(rows: Knowledge[], originRows: Knowledge[]) {
	rows.filter(row => !!originRows.find(originRow => originRow.id === row.id)).forEach(async row => {
		await prisma.knowledge.update({ where: { id: row.id }, data: row })
	});
	rows.filter(row => !originRows.find(originRow => originRow.id === row.id)).forEach(async row => {
		await prisma.knowledge.create({data: row})
	});
	originRows.filter(originRow => !rows.find(row => originRow.id === row.id)).forEach(async row => {
		await prisma.knowledge.delete({ where: { id: row.id } })
	});
}
